package kbpost

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/blog/rpc/blogclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type RemovePostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRemovePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RemovePostLogic {
	return &RemovePostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RemovePostLogic) RemovePost(req *types.RemoveKBEntryReq) (*types.BaseMsgResp, error) {
	if len(req.Ids) == 0 {
		return &types.BaseMsgResp{
			Success: true,
		}, nil
	}

	res, err := l.svcCtx.BlogRpc.DeleteKBPost(l.ctx, &blogclient.IDsReq{
		Ids: req.Ids,
	})
	if err != nil {
		return nil, err
	}

	//从推荐系统中移除
	var ids []string
	for _, v := range req.Ids {
		if v > 0 {
			ids = append(ids, globalkey.GorseKnowledgeBasePrefix+strconv.FormatUint(v, 10))
		}
	}
	if len(ids) > 0 {
		err := l.deleteGorseLogic(ids)
		if err != nil {
			logx.Errorf("RemovePost deleteItem Error: %+v", err)
		}
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}

func (l *RemovePostLogic) deleteGorseLogic(ids []string) error {
	return l.svcCtx.GorseClient.DeleteItem(
		l.svcCtx.Config.Query.GorseUrl,
		strings.Join(ids, ","),
	)
}
